import pymysql
from movie_dao import MovieDAO
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

from urllib.parse import quote  # 导入URL编码工具

class FilmReelDAO:
    def __init__(self):
        self.movie_dao = MovieDAO()
        self.default_poster = '/static/default_poster.jpg'  # 默认海报路径（可选）
        self.proxy_base = 'http://127.0.0.1:5000/api/proxy-image'  # 代理接口基址

    def get_film(self):
        conn = None
        cursor = None
        try:
            conn = self.movie_dao.get_connection()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            cursor.execute("""
                SELECT title, rating, year, director, genre, intro, rank_num, poster 
                FROM movies ORDER BY rating DESC
            """)
            movie_list = cursor.fetchall()
            
            if not movie_list:
                return self.default_movies
            
            for movie in movie_list:
                poster = movie.get('poster', '')
                if not poster:
                    movie['poster'] = self.default_poster  # 无URL时用默认海报
                else:
                    # 处理豆瓣图片URL（关键步骤）
                    if 'doubanio.com' in poster:
                        encoded_url = quote(poster)  # 编码URL避免特殊字符问题
                        movie['poster'] = f"{self.proxy_base}?url={encoded_url}"
            
            return movie_list
        except Exception as e:
            logger.error(f"错误: {str(e)}")
            return self.default_movies
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()